package com.CityHunter.Activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.CityHunter.R;
import com.CityHunter.Common.Http;
import com.CityHunter.Request.RegisterRequest;

public class RegisterPage extends Activity {
	private boolean valid, emailCheck, agreementCheck, emptyCheck;

	// Declare buttons
	private Button regp_btn_register;

	// Declare EditText
	private EditText regp_et_email;
	private EditText regp_et_password;
	private EditText regp_et_name;

	// Declare CheckBox
	private CheckBox regp_cb_agreement;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regp);

		valid = false;
		emailCheck = false;
		// passwordCheck = false;
		agreementCheck = false;
		emptyCheck = false;

		// Mapping buttons
		regp_btn_register = (Button) findViewById(R.id.regp_btn_register);
		regp_btn_register.setClickable(valid);

		// Mapping EditText
		regp_et_email = (EditText) findViewById(R.id.regp_et_email);
		regp_et_password = (EditText) findViewById(R.id.regp_et_password);
		regp_et_name = (EditText) findViewById(R.id.regp_et_name);

		// Mapping CheckBox
		regp_cb_agreement = (CheckBox) findViewById(R.id.regp_cb_agreement);

		// Set Listener for buttons
		regp_btn_register.setOnClickListener(handleRegister);

		// Set Listener for EditText
		regp_et_email.setOnFocusChangeListener(checkEmailFormat);
		// regp_et_password.setOnFocusChangeListener(checkPasswordLength);

		// Set Listener for CheckBox
		regp_cb_agreement.setOnCheckedChangeListener(checkAgreement);
	}

	private void checkEmptyFiled() {
		if (regp_et_email.getText().length() > 0
				&& regp_et_password.getText().length() > 0
				&& regp_et_name.getText().length() > 0)
			emptyCheck = true;
		Log.d("regp_Debug", "Email Length : "
				+ regp_et_email.getText().length() + " Password Length : "
				+ regp_et_password.getText().length() + " Name Length"
				+ regp_et_name.getText().length());
	}

	private void checkState() {
		checkEmptyFiled();
		if (emailCheck && agreementCheck && emptyCheck) {
			valid = true;
			regp_btn_register.setVisibility(View.VISIBLE);
		} else {
			Log.d("regp_Debug", "emailCheck : " + emailCheck
					+ " agreementCheck : " + agreementCheck + " emptyCheck : "
					+ emptyCheck);
			regp_btn_register.setVisibility(View.GONE);
		}
	}

	// Implement listener
	private OnClickListener handleRegister = new OnClickListener() {
		public void onClick(View v) {

			// Get String from EditTexts
			String email = regp_et_email.getText().toString();
			String password = regp_et_password.getText().toString();
			String name = regp_et_name.getText().toString();

			// Get url from strings.xml
			String registerPage = getString(R.string.url_registerPage);

			RegisterRequest rr = new RegisterRequest(registerPage);
			int result = rr.sendRequest(email, password, name);

			// Handle Register
			if (result == 1) {
				Toast.makeText(RegisterPage.this, "User created.",
						Toast.LENGTH_LONG).show();
				RegisterPage.this.finish();
			} else {
				Toast.makeText(RegisterPage.this, "User create failed.",
						Toast.LENGTH_LONG).show();
			}
		}
	};

	// Implement Listener
	private OnFocusChangeListener checkEmailFormat = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			String email = regp_et_email.getText().toString();

			// If focus changed
			if (!hasFocus) {
				// If email format is incorrect
				if (!email.endsWith(".com") && email.indexOf("@") <= 0) {
					Toast.makeText(RegisterPage.this,
							"email format is incorrect!", Toast.LENGTH_LONG)
							.show();
					emailCheck = false;
				} else {

					// If email format is correct, check existing user
					String checkExistUserPage = getString(R.string.url_checkExistUser);

					int result = 1;

					// Declare NameValuePair to store the data
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("email", email));

					// Send Register Request
					Http http = new Http();
					Log.d("Sttp_Debug", "Sending Request : "
							+ checkExistUserPage);
					JSONArray jsonResponse = http.sendRequest(
							checkExistUserPage, params);
					try {
						result = Integer.parseInt(jsonResponse.getJSONObject(0)
								.getString("match_no"));
						Log.d("Sttp_Debug", "Server Response : match_no = "
								+ result);
					} catch (Exception e) {
						Log.e("Sttp_Error", e.getMessage().toString());
					}

					if (result == 0) {
						Toast.makeText(RegisterPage.this,
								"You can use this E-mail.", Toast.LENGTH_LONG)
								.show();
						emailCheck = true;
					} else {
						Toast.makeText(RegisterPage.this,
								"Same user already exist.", Toast.LENGTH_LONG)
								.show();
						emailCheck = false;
					}
				}
			}
			checkState();
		}
	};

	/*
	 * // Implement edit text password focus change listener private
	 * OnFocusChangeListener checkPasswordLength = new OnFocusChangeListener() {
	 * 
	 * @Override public void onFocusChange(View v, boolean hasFocus) { String
	 * password = regp_et_password.getText().toString();
	 * 
	 * // If focus changed if (!hasFocus) { // If the length of password is
	 * smaller than 6 if (password.length() < 6) { Toast.makeText(Register.this,
	 * "Password is too short!", Toast.LENGTH_LONG).show(); passwordCheck =
	 * false; } else { passwordCheck = true; } } checkState(); } };
	 */

	// Implement Check Box On Checked Change Listener
	private OnCheckedChangeListener checkAgreement = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (regp_cb_agreement.isChecked())
				agreementCheck = true;
			checkState();
		}
	};
}